<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/6
 * Time: 13:48
 */

namespace App\WebSocket;

use EasySwoole\Socket\Bean\Caller;
use EasySwoole\Socket\Bean\Response;
use EasySwoole\Socket\AbstractInterface\ParserInterface;

class WebSocketParser implements ParserInterface
{
    /**
     * 解码上来的消息
     * @param $raw
     * @param $client
     * @return Caller|null
     */
    public function decode($raw, $client): ?Caller
    {
        $caller = new Caller();
        if( $raw !== 'PING' ){
            $payload = json_decode($raw,true);
            $class = $payload['controller'] ?? 'index';
            $action = $payload['action'] ?? 'actionNotFount';
            $params = isset($payload['params']) ? (array)$payload['params'] : [];
            $controllerClass = "\\App\\WebSocket\\Controller\\".ucfirst($class);
            if(!class_exists($controllerClass)) $controllerClass = "\\App\\WebSocket\\Controller\\Index";
            $caller->setClient($caller);
            $caller->setControllerClass($controllerClass);
            $caller->setAction($action);
            $caller->setArgs($params);
        }else{
            $caller->setControllerClass("\\App\\WebSocket\\Controller\\Live");
            $caller->setAction('heartbeat');
        }
        return $caller;
    }

    /**
     * 打包下发的消息
     * @param Response $response
     * @param $client
     * @return string|null
     */
    public function encode(Response $response, $client): ?string
    {
        return $response->getMessage();
    }
}